package com.xbj.voa.service.impl;

import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.xbj.voa.db.dao.TbUserDao;
import com.xbj.voa.db.pojo.TbUser;
import com.xbj.voa.exception.VoaException;
import com.xbj.voa.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Set;

/**
 * @author: 木火
 * @create: 2024-01-13
 * @description:
 **/
@Service
@Scope("prototype")  //因为要操作ThreadLocalToken
public class UserServiceImpl implements UserService {
    private static Logger LOG = LoggerFactory.getLogger(UserServiceImpl.class);

    @Value("${wx.app-id}")
    private String appId;

    @Value("${wx.app-secret}")
    private String appSecret;

    @Resource
    private TbUserDao tbUserDao;

    /**
     * @Author 木火
     * @Date  2024/1/13
     * @Param   registerCode:注册邀请码  code:临时授权字符串 nickName:微信昵称 photo:微信头像地址
     * @Return 用户id
     * @Description 用户注册
     **/
    @Override
    public int registerUser(String registerCode, String code, String nickName, String photo) {
        //判断是否为管理员注册
        if(StringUtils.equals("000000",registerCode)){
            //是管理员注册,则判断是否已存在超级管理员
            boolean b = tbUserDao.haveRootUser();
            if(!b){
                //不存在
                //根据临时授权字符串获取长期授权字符串
                String openId = getOpenId(code);

                //将当前用户设置为超级管理员
                HashMap hashMap = new HashMap();
                hashMap.put("openId", openId);
                hashMap.put("nickname", nickName);
                hashMap.put("photo", photo);
                hashMap.put("role", "[0]");
                hashMap.put("status", 1);
                hashMap.put("createTime", new Date());
                hashMap.put("root", true);
                tbUserDao.insert(hashMap);
                Integer userId = tbUserDao.searchIdByOpenId(openId);
                return userId;
            }else {
                //存在,返回错误信息
                LOG.info("超级管理员已存在,注册失败");
                throw new VoaException("超级管理员已存在,注册失败");
            }

        }
            //不是超级管理员注册

        return 0;
    }

    /**
     * @Author 木火
     * @Date  2024/1/14
     * @Param
     * @Description 根据用户id获取用户权限列表
     **/
    @Override
    public Set<String> searchUserPermissions(int userId) {
        Set<String> permissions = tbUserDao.searchUserPermissions(userId);
        return permissions;
    }

    /**
     * @Author 木火
     * @Date  2024/1/15
     * @Param
     * @Description 用户登陆
     **/
    @Override
    public Integer login(String code) {
        //根据临时授权字符串,查询用户长期授权字符串
        String openId = getOpenId(code);
        // 根据长期授权字符串查询用户是否存在
        Integer userId = tbUserDao.searchIdByOpenId(openId);
        //不存在抛出异常
        if(userId == null){
            throw new VoaException("用户不存在");
        }
        //存在,返回用户id
        return userId;
    }

    /**
     * @Author 木火
     * @Date  2024/1/13
     * @Param code:临时授权字符串
     * @Description :根据临时授权字符串请求微信,获取长期授权字符串
     **/
    private String getOpenId(String code) {
        String openId = "";
        try {
            String url = "https://api.weixin.qq.com/sns/jscode2session";
            HashMap map = new HashMap();
            map.put("appid", appId);
            map.put("secret", appSecret);
            map.put("js_code", code);
            map.put("grant_type", "authorization_code");
            String response = HttpUtil.post(url, map);
            JSONObject json = JSONUtil.parseObj(response);
            openId = json.getStr("openid");
            if (StringUtils.isBlank(openId)) {
                throw new RuntimeException("临时登陆凭证错误");
            }
        } catch (RuntimeException e) {
            LOG.info("根据临时授权字符串请求微信,获取长期授权字符串报错",e);
            throw new RuntimeException("临时登陆凭证错误");
        }
        return openId;
    }

}
